<template>
  <div class="ds-binding-page">
    <el-card>
      <div class="header-bar">
        <span class="title">动态数据绑定</span>
      </div>
      <el-row :gutter="20">
        <!-- 左：模拟报表/大屏组件 -->
        <el-col :span="24">
          <div class="panel-title">可绑定组件</div>
          <el-table :data="bindTargetList" border style="margin-bottom: 16px">
            <el-table-column prop="name" label="组件名称" min-width="130"/>
            <el-table-column prop="type" label="类型" min-width="90">
              <template #default="scope">
                <el-tag>{{ scope.row.type }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="当前绑定数据源" min-width="160">
              <template #default="scope">
                <span v-if="scope.row.dataSourceId">
                  {{ getDSName(scope.row.dataSourceId) }}
                  <el-button text size="small" style="color: red;" @click="unbindDS(scope.row)">解绑</el-button>
                </span>
                <span v-else style="color:#ccc;">未绑定</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="110">
              <template #default="scope">
                <el-button size="small" @click="openBindDialog(scope.row)">绑定数据源</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-card>

    <!-- 绑定数据源弹窗 -->
    <el-dialog v-model="bindDialogVisible" title="选择数据源" width="360px">
      <el-select v-model="bindSelectId" placeholder="请选择要绑定的数据源" style="width:100%">
        <el-option
          v-for="item in dsList"
          :key="item.id"
          :label="item.name + '（' + getTypeName(item.type) + '）'"
          :value="item.id"
        />
      </el-select>
      <template #footer>
        <el-button @click="bindDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmBind">绑定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

// 加载全部数据源
const dsList = ref([])
function loadDSList() {
  dsList.value = JSON.parse(localStorage.getItem('dsList') || '[]')
}

// 模拟可绑定组件（报表、大屏等）
const bindTargetList = ref([])
const defaultTargets = [
  { id: 1, name: '月度销售报表', type: '报表', dataSourceId: null },
  { id: 2, name: '生产监控大屏', type: '大屏', dataSourceId: null },
  { id: 3, name: '客户分析报表', type: '报表', dataSourceId: null }
]
function loadBindTargets() {
  const local = JSON.parse(localStorage.getItem('bindTargetList') || 'null')
  if (!local) {
    localStorage.setItem('bindTargetList', JSON.stringify(defaultTargets))
    bindTargetList.value = defaultTargets
  } else {
    bindTargetList.value = local
  }
}

// 数据源类型
const dsTypes = [
  { value: 'api', label: 'API接口' },
  { value: 'db', label: '数据库' },
  { value: 'excel', label: 'Excel文件' }
]
function getTypeName(type) {
  const found = dsTypes.find(t => t.value === type)
  return found ? found.label : type
}
function dsTypeTag(type) {
  if (type === 'api') return 'success'
  if (type === 'db') return 'warning'
  if (type === 'excel') return 'info'
  return ''
}
function getDSName(id) {
  const found = dsList.value.find(ds => ds.id === id)
  return found ? found.name : ''
}

// 绑定弹窗
const bindDialogVisible = ref(false)
const bindSelectId = ref(null)
const bindTarget = ref(null)
function openBindDialog(row) {
  bindTarget.value = row
  bindSelectId.value = row.dataSourceId || null
  bindDialogVisible.value = true
}
function confirmBind() {
  if (!bindSelectId.value) {
    ElMessage.warning('请选择数据源！')
    return
  }
  // 更新绑定
  bindTarget.value.dataSourceId = bindSelectId.value
  // 持久化
  const arr = bindTargetList.value.map(t =>
    t.id === bindTarget.value.id ? { ...bindTarget.value } : t
  )
  localStorage.setItem('bindTargetList', JSON.stringify(arr))
  bindTargetList.value = arr
  bindDialogVisible.value = false
  ElMessage.success('绑定成功！')
}

// 解绑
function unbindDS(row) {
  row.dataSourceId = null
  const arr = bindTargetList.value.map(t =>
    t.id === row.id ? { ...row } : t
  )
  localStorage.setItem('bindTargetList', JSON.stringify(arr))
  bindTargetList.value = arr
  ElMessage.success('已解绑！')
}

onMounted(() => {
  loadDSList()
  loadBindTargets()
})
</script>

<style scoped>
.ds-binding-page {
  padding: 24px;
  background: #f7f8fa;
  min-height: 95vh;
}
.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}
.title {
  font-size: 20px;
  font-weight: 600;
}
.panel-title {
  font-size: 15px;
  font-weight: 600;
  margin-bottom: 8px;
  color: #1677ff;
}
</style>
